package com.appfront;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.appfront.debug.App;
import com.auxtools.CrashHandler;
import com.auxtools.CreatePDF;
import com.auxtools.LINE;
import com.rtuwrapper.messaging.ModbusException;
import com.rtuwrapper.messaging.ReadFloatRequest;
import com.rtuwrapper.messaging.ReadFloatResponse;
import com.rtuwrapper.messaging.ReadIntegerRequest;
import com.rtuwrapper.messaging.ReadIntegerResponse;
import com.rtuwrapper.messaging.ReadRegisterRequest;
import com.rtuwrapper.messaging.ReadRegisterResponse;
import com.uicontrol.RoundCountDown;
import com.uicontrol.RoundProgressBar;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import lecho.lib.hellocharts.formatter.ColumnChartValueFormatter;
import lecho.lib.hellocharts.formatter.SimpleColumnChartValueFormatter;
import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.LineChartView;

import static com.appfront.LoginActivity.transaction;

public class MainActivity extends Activity {


    LinearLayout main_view_chart_line;
    LinearLayout main_view_chart_bar;
    LineChartView   chart_line;
    ColumnChartView chart_bar;

    TextView text_userID;
    TextView text_userID_label;
    TextView text_planName;
    TextView text_planName_label;
    TextView text_force;
    TextView text_power;
    TextView text_time;
    TextView text_nowGroups;
    TextView text_totalGroups;
    TextView text_totalGroups_label;
    Button  button_stop;
    /* 读数据线程 */
    boolean isQuitNow = false;      // 用于当前activity退出时，结束read线程
    Mhandler mhandler;
    Errhandler ehandler;
    /* 绘图数据 */
    private List<Line>  chartLines = new ArrayList<Line>();
    private LineChartData lineChartData = new LineChartData();
    LINE forceLineRaw;
    LINE forceLineCubic;
    LINE forceLineFreq;
    private ColumnChartData barData;
    /* 运动数据采集 */
    int now_group = 0;
    int now_freqs = 0;
    List<Long> freq_timeStart_ms = new ArrayList<Long>();
    boolean is_now_freqs_started = false;
    boolean is_now_freqs_timeouted = false;
    boolean is_now_group_started = false;
    float now_freq_maxPower = 0;
    float now_freq_maxForce = 0;
    float now_freq_maxForceTime = 0;
    long group_startTime_ms = 0;
    /* 存储数据定义 */
    ArrayList<ArrayList<Float>> max_power;
    ArrayList<ArrayList<Float>> max_force;
    ArrayList<ArrayList<Float>> dur_times;
    ArrayList<Float> sub_max_power;
    ArrayList<Float> sub_max_force;
    ArrayList<Float> sub_dur_times;
    ArrayList<Bitmap> PowFore_bitmaps;
    ArrayList<Bitmap> DurTime_bitmaps;
    /* layout界面调整 */
    LinearLayout layout_countdown;
    LinearLayout layout_normal;
    RoundCountDown roundCountDown;
    TextView rountCountDownInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CrashHandler.getInstance().init(this);

        setContentView(R.layout.activity_main);
        chart_line = (LineChartView) findViewById(R.id.chart_line);     //折线图
        chart_bar = (ColumnChartView) findViewById(R.id.chart_bar);     //柱形图
        main_view_chart_line = (LinearLayout) findViewById(R.id.main_view_chart_line);
        main_view_chart_bar  = (LinearLayout) findViewById(R.id.main_view_chart_bar);
        text_userID = (TextView) findViewById(R.id.main_userID);
        text_userID_label = (TextView) findViewById(R.id.main_userID_label);
        text_planName = (TextView) findViewById(R.id.main_planName);
        text_planName_label = (TextView) findViewById(R.id.main_planName_label);
        text_force = (TextView) findViewById(R.id.main_force);
        text_power = (TextView) findViewById(R.id.main_power);
        text_time = (TextView) findViewById(R.id.main_time);
        text_totalGroups = (TextView) findViewById(R.id.main_countTotal);
        text_totalGroups_label = (TextView) findViewById(R.id.main_countTotal_label);
        text_nowGroups = (TextView) findViewById(R.id.main_countNow);
     //   forceProgressBar = (RoundProgressBar) findViewById(R.id.main_progressBar);
        button_stop = (Button) findViewById(R.id.main_stopButton);
        layout_countdown = (LinearLayout) findViewById(R.id.main_layout_countdown);
        layout_normal = (LinearLayout) findViewById(R.id.main_layout_normal);
        roundCountDown = (RoundCountDown) findViewById(R.id.main_countdown_progressBar);
        rountCountDownInfo = (TextView) findViewById(R.id.main_countdown_text);
        layout_switchShow(true);
        if(TestproSetup.usrID == ""){
            text_userID.setVisibility(View.INVISIBLE);
            text_planName.setVisibility(View.INVISIBLE);
            text_planName_label.setVisibility(View.INVISIBLE);
            text_userID_label.setVisibility(View.INVISIBLE);
            text_totalGroups_label.setVisibility(View.INVISIBLE);
            text_totalGroups.setVisibility(View.INVISIBLE);
        }

        text_userID.setText(TestproSetup.usrID);
        text_planName.setText(TestproSetup.getCurPlanName());
        text_force.setText("0N");
        text_power.setText("0W");
        text_time.setText("0.0S");
        text_nowGroups.setText(0 + "组" + 0 + "次");
        text_totalGroups.setText(Integer.toString(TestproSetup.getCurGroup()));

        max_force = new ArrayList<ArrayList<Float>>();
        max_power = new ArrayList<ArrayList<Float>>();
        dur_times = new ArrayList<ArrayList<Float>>();
        sub_max_force = new ArrayList<Float>();
        sub_max_power = new ArrayList<Float>();
        sub_dur_times = new ArrayList<Float>();
        PowFore_bitmaps = new ArrayList<Bitmap>();
        DurTime_bitmaps = new ArrayList<Bitmap>();

        /* 初始化图表 */
        forceLineRaw = new LINE(chartLines, Color.parseColor("#00BFFF"));
        forceLineCubic = new LINE(chartLines, Color.BLUE);
        forceLineFreq = new LINE(chartLines, Color.BLACK);
        chartLines.remove(forceLineFreq.line);
        forceLineRaw.setMaxLineLen(800);
        forceLineCubic.setMaxLineLen(800);
        forceLineFreq.setMaxLineLen(800);
        if(!TestproSetup.isForceRawShow)
            chartLines.remove(forceLineRaw.line);
        if(!TestproSetup.isForceCubicShwo)
            chartLines.remove(forceLineCubic.line);
        initLineChart();
        initBarChart();

        mhandler = new Mhandler();
        ehandler = new Errhandler();

        if (true == LoginActivity.isConnected) {
            read_thread.setPriority(Thread.MAX_PRIORITY);
            startNewGroupTest();
            read_thread.start();
        }

        button_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {   //提前终止
                endTotalTest(false);
            }
        });
        App.VerifyStoragePermissions(this);
    }

    Thread read_thread = new Thread(new Runnable() {
        @Override
        public void run() {
            Message msg = mhandler.obtainMessage();
            Message errmsg = ehandler.obtainMessage();
            Bundle bundle = new Bundle();
            ReadIntegerRequest request = new ReadIntegerRequest();
            ReadIntegerResponse response;
            int err_count = 0;
            int readValue = 0;
            request.setData(0, readValue);
            while (true){
                if(isQuitNow){
                    return;
                }
                if(false == is_now_group_started) {
                    App.sleep_ms(20);
                    continue;
                }else
                    App.sleep_ms(4);
                try {
                    transaction.execute(request);
                } catch (ModbusException e) {
                    App.sleep_ms(20);
                    err_count++;
                    if(err_count > 100){
                        err_count = 0;
                        bundle.clear();
                        bundle.putString("err", "no response");
                        errmsg = ehandler.obtainMessage();
                        errmsg.setData(bundle);
                        ehandler.sendMessage(errmsg);
                    }
                    continue;
                }
                try {
                    response = (ReadIntegerResponse) transaction.getResponse();
                    readValue = response.getValue();
                } catch (ModbusException e) {
                    App.sleep_ms(20);
                    bundle.clear();
                    bundle.putString("err", e.toString());
                    errmsg = ehandler.obtainMessage();
                    errmsg.setData(bundle);
                    ehandler.sendMessage(errmsg);
                    continue;
                }
                bundle = new Bundle();
                bundle.putFloat("f", readValue - TestproSetup.forceBase);
                msg = mhandler.obtainMessage();
                msg.setData(bundle);
                mhandler.sendMessage(msg);
            }
        }
    });

    private boolean last_layout_show = false;
    private void layout_switchShow(boolean normal){

        if(last_layout_show != normal){
            last_layout_show = normal;
        }else{
            return;
        }
        if(normal){
            layout_countdown.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 0));
            layout_normal.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1));
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) layout_normal.getLayoutParams();
            params.setMargins(50, 50, 0, 0);
            layout_normal.setLayoutParams(params);
        }else{
            layout_countdown.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1));
            layout_normal.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 0));
            roundCountDown.setMax(TestproSetup.getCurPeakForceTime());
            roundCountDown.setProgress(TestproSetup.getCurPeakForceTime());
            rountCountDownInfo.setText("请维持弹力带，等待倒计时结束！");
        }
    }

    private float getAbsForce(float raw_f){
        return Math.abs(raw_f-0);
    }

    class Mhandler extends Handler {
        Bundle bundle;
        LINE.TREND last_trend = LINE.TREND.NONE;
        int refresh_count = 0;
        public Mhandler() { }
        public Mhandler(Looper L) {
            super(L);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            bundle  = msg.getData();
            float now_force = bundle.getFloat("f");                // Y值
            now_force = getAbsForce(now_force);                     // 获取绝对值
            long now_time_ms = System.currentTimeMillis();          // X值
            float xAxisValue = (float)((now_time_ms-group_startTime_ms)*0.001);

            if(false == is_now_group_started)
                return;

            // 刷新曲线图
            forceLineRaw.add(xAxisValue, now_force);
            float cublicData = forceLineRaw.getCublicValue(TestproSetup.cubicNums, TestproSetup.cubicNomax);
            forceLineCubic.add(xAxisValue, cublicData);
            forceLineFreq.add(xAxisValue, cublicData);
            chart_line.setLineChartData(lineChartData);
            Viewport viewport = chart_line.getMaximumViewport();
            float topValue = viewport.top;
            float botValue = viewport.bottom;
            if(topValue - botValue < 15){
                topValue += 10;
                botValue -= 10;
                viewport.top = topValue;
                viewport.bottom = botValue;
                chart_line.setMaximumViewport(viewport);
                chart_line.setCurrentViewport(viewport);
            }

            now_force = cublicData;
            /* 判断趋势 */
            float temp_power = forceLineCubic.getNowPower();
            if(now_freq_maxPower < temp_power)              //本次最大功率值计算
                now_freq_maxPower = temp_power;
            if(now_freq_maxForce < Math.abs(now_force))     //本次最大拉力计算
                now_freq_maxForce = Math.abs(now_force);
            LINE.TREND trend = forceLineCubic.trendJudge();
            if(false == is_now_freqs_started) {
                if(trend == LINE.TREND.JUSTUP){         // 上升沿
                    is_now_freqs_started = true;
                    freq_timeStart_ms.add(now_time_ms);
                    now_freq_maxForce = 0;
                    now_freq_maxForceTime = 0;
                    forceLineFreq.clear();
                    if(true == is_now_freqs_timeouted){
                        is_now_freqs_timeouted = false;
                        alertDialog_show.dismiss();
                        isProgressCountQuited = true;
                    }
                }
            }else {
                /* 当前次结束判断 */
                if(last_trend == LINE.TREND.JUSTDOWN && trend == LINE.TREND.NONE) {
                    if(now_force < now_freq_maxForce - 8){
                        is_now_freqs_started = false;
                        now_freqs++;
                        text_nowGroups.setText(now_group + "组" + now_freqs + "次");
                        sub_max_force.add(now_freq_maxForce);
                        sub_max_power.add(now_freq_maxPower);
                        float durTimes = forceLineFreq.getDurTimes(now_freq_maxForce);
                        sub_dur_times.add(durTimes);
                        if(TestproSetup.usrID == ""){
                            if(sub_max_force.size() > 10)
                                sub_max_force.remove(0);
                            if(sub_max_power.size() > 10)
                                sub_max_power.remove(0);
                            if(sub_dur_times.size() > 10)
                                sub_dur_times.remove(0);
                        }
                        addBarChart(now_freq_maxForce, now_freq_maxPower, durTimes);
                        now_freq_maxForce = 0;
                        now_freq_maxPower = 0;
                        forceLineFreq.clear();

                        if(now_freqs >= TestproSetup.getCurFreqs() && TestproSetup.usrID!=""){            //当前组完成
                            //App.toast("当前组测试完成", App.DEBUG_LEVEL.INFO);
                            is_now_group_started = false;
                            if(now_group >= TestproSetup.getCurGroup()){
                                isProgressCountQuited = true;
                                max_force.add(sub_max_force);
                                max_power.add(sub_max_power);
                                dur_times.add(sub_dur_times);
                                PowFore_bitmaps.add(getBitmap(chart_bar));
                                DurTime_bitmaps.add(getBitmap(chart_line));
                                startNewGroupTest();
                            }else {
                                try {
                                    showCountdownDialog("休息时间", "当前测试组完成，请休息" + TestproSetup.getCurGroupTime() + "秒后，开始下一组测试",
                                            TestproSetup.getCurGroupTime(), "直接开始下组", "结束测试");
                                } catch (NoSuchFieldException e) {
                                    e.printStackTrace();
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }else{          //到达峰值力判断

                    boolean isBanlance = false;
                    if(TestproSetup.getIsStartForce()){                     //根据是否到达 力限值进行判断
                        if(now_force > TestproSetup.getStartForceN()){
                            isBanlance = true;
                        }
                    }else{                                              //根据是否拉力平衡进行判断
                        isBanlance = forceLineCubic.isBanlance(5);
                    }
                    if(0 == now_freq_maxForceTime){
                        now_freq_maxForceTime = 5*23/1000;
                    }

                    if(TestproSetup.usrID != "")
                    if(now_freq_maxForceTime > TestproSetup.getCurPeakForceTime()){
                        if(isBanlance){
                            rountCountDownInfo.setText("请恢复弹力带，然后开始下一组测试！");
                        }else{
                            layout_switchShow(true);
                        }
                    }else{
                        if(isBanlance && now_force > 12){
                            now_freq_maxForceTime += forceLineCubic.getLastStepTimes();
                        }else{
                            now_freq_maxForceTime -= (12/(now_force>1?now_force:1))*forceLineCubic.getLastStepTimes();
                        }
                        if(now_freq_maxForceTime > 0.3  && now_force > now_freq_maxForce*TestproSetup.forceScaleMax){
                            layout_switchShow(false);
                            roundCountDown.setProgress((int)(TestproSetup.getCurPeakForceTime()-now_freq_maxForceTime));
                        }else{
                            layout_switchShow(true);
                        }
                    }
                }
            }
            last_trend = trend;
            int lens = freq_timeStart_ms.size();
            if(false == is_now_freqs_timeouted && lens > 0) {
                if (now_time_ms - freq_timeStart_ms.get(lens - 1) > 30 * 1000) {    // 次超时判断
                    is_now_freqs_timeouted = true;
                    try {
                        showCountdownDialog("当前次数超时", "请拉动弹力带进行下一次测试，超时（" + TestproSetup.getCurFreqsTime() + "S）将提前结束本组测试",
                                TestproSetup.getCurFreqsTime() - 30, "进入下一组", "结束测试");
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }

            // 刷新右侧显示参数
            refresh_count++;
            if(refresh_count % 4 == 0){
                text_nowGroups.setText(now_group + "组" + now_freqs + "次");
                text_force.setText(String.format("%.1fN", now_force));
                text_power.setText(String.format("%.1f", temp_power));
                text_time.setText(String.format("%.1fS", xAxisValue));
           //     forceProgressBar.setProgress(Math.abs((int)now_force));
            }
        }
    }

    /**     * 获取Layout截图     *     * @return 所需区域的截图     */
    private Bitmap getBitmap(View v) {
        //View view = v.getRootView();
        View view = v;
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();                                       //启用DrawingCache并创建位图
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());    //创建一个DrawingCache的拷贝，因为DrawingCache得到的位图在禁用后会被回收

        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        view.draw(canvas);

        view.setDrawingCacheEnabled(false);                             //禁用DrawingCahce否则会影响性能
        return bitmap;
    }

    private void showReportDialog(final Context context){

        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        //normalDialog.setIcon(R.drawable.curve);
        normalDialog.setTitle("测试报告");
        normalDialog.setMessage("现在查看测试报告吗?");
        normalDialog.setPositiveButton("预览",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        CreatePDF.CreateFile(context, PowFore_bitmaps, DurTime_bitmaps, TestproSetup.getCurGroup(),
                                max_force, max_power, dur_times);
                        finish();
                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        App.toast("预览已取消", App.DEBUG_LEVEL.INFO);
                        finish();
                    }
                });
        // 显示
        normalDialog.show();
    }

    boolean isProgressCountQuited = false;
    AlertDialog alertDialog_show = null;
    private void showCountdownDialog(final String title, String detail, final int count_s, String enter, String cancel) throws NoSuchFieldException, IllegalAccessException {
        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
        LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
        View view = inflater.inflate(R.layout.countdown_dialog, null);
        alertDialog.setView(view);
        alertDialog.setTitle(title);
        TextView textView = (TextView) view.findViewById(R.id.dialog_text);
        textView.setText(detail);
        final RoundProgressBar roundProgressBar = (RoundProgressBar) view.findViewById(R.id.dialog_progressBar);
        roundProgressBar.setStyle(false);
        roundProgressBar.setCricleColor(Color.RED);
        roundProgressBar.setCricleProgressColor(Color.BLUE);
        roundProgressBar.setMax(count_s*1000);
        /* 直接进入下一组 */
        alertDialog.setPositiveButton(enter,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        isProgressCountQuited = true;
                        max_force.add(sub_max_force);
                        max_power.add(sub_max_power);
                        dur_times.add(sub_dur_times);
                        PowFore_bitmaps.add(getBitmap(chart_bar));
                        DurTime_bitmaps.add(getBitmap(chart_line));
                        startNewGroupTest();
                    }
                });
        /* 结束测试 */
        alertDialog.setNegativeButton(cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        endTotalTest(false);
                    }
                });

        alertDialog_show = alertDialog.show();
        //通过反射修改title字体大小和颜色
        Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
        mAlert.setAccessible(true);
        Object mAlertController = mAlert.get(alertDialog_show);
        Field mTitle = mAlertController.getClass().getDeclaredField("mTitleView");
        mTitle.setAccessible(true);
        final TextView mTitleView = (TextView) mTitle.get(mAlertController);
        //mTitleView.setTextSize(32);
        //mTitleView.setTextColor(Color.RED);
        isProgressCountQuited = false;
        class ProgressHandler extends Handler {
            Bundle bundle;     //建立一个装数据用的箱子

            public ProgressHandler() { }
            public ProgressHandler(Looper L) {
                super(L);
            }

            @Override
            public void handleMessage(Message msg) {       //当有从另一线程传来的消息时 这里开始运行
                super.handleMessage(msg);
                bundle  = msg.getData();                    //msg是从另一线程传来的数据 ，先用箱子捕获数据
                int time_S = bundle.getInt("time_S");
                mTitleView.setText(title + ": " + (count_s - time_S) + "S");
            }
        }
        final ProgressHandler progressHandler = new ProgressHandler();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                int count_i = 0;
                int progress = 0;
                Message message;
                Bundle bundle = new Bundle();
                while (true){
                    if(isProgressCountQuited)
                        return;

                    count_i++;
                    App.sleep_ms(100);
                    progress = count_s*1000 - count_i*100;
                    roundProgressBar.setProgress(progress);
                    if(count_i %10 == 0){
                        bundle.clear();
                        bundle.putInt("time_S", count_i/10);
                        message = progressHandler.obtainMessage();
                        message.setData(bundle);
                        progressHandler.sendMessage(message);
                    }
                    if(progress <= 0){
                        if(null != alertDialog_show)
                            alertDialog_show.dismiss();
                        startNewGroupTest();
                        return;
                    }
                }
            }
        });
        thread.start();
    }

    /* 测试完成，这里进行数据保存，并提示是否打印/预览测试报告
    *  normal: 是否是正常结束
    * */
    void endTotalTest(boolean normal){
        //App.toast("总测试完成: " + (normal?"正常结束":"异常结束"), App.DEBUG_LEVEL.INFO);
        if(false == normal){
            isProgressCountQuited = true;
            max_force.add(sub_max_force);
            max_power.add(sub_max_power);
            dur_times.add(sub_dur_times);
            PowFore_bitmaps.add(getBitmap(chart_bar));
            DurTime_bitmaps.add(getBitmap(chart_line));
        }
        if(max_force.get(0).size() > 0)
            showReportDialog(this);
        else
            finish();
    }

    class Errhandler extends Handler {
        Bundle bundle;     //建立一个装数据用的箱子

        public Errhandler() { }
        public Errhandler(Looper L) {
            super(L);
        }

        @Override
        public void handleMessage(Message msg) {       //当有从另一线程传来的消息时 这里开始运行
            super.handleMessage(msg);
            bundle  = msg.getData();                    //msg是从另一线程传来的数据 ，先用箱子捕获数据
            String errstr = bundle.getString("err");
            App.toast(errstr, App.DEBUG_LEVEL.DEBUG);
        }
    }

    private void initLineChart(){

        lineChartData.setLines(chartLines);
        //坐标轴
        Axis axisX = new Axis();            //X轴
        axisX.setHasTiltedLabels(true);     //X坐标轴字体是斜的显示还是直的，true是斜的显示
        //axisX.setTextColor(Color.BLUE);    //设置字体颜色
        //axisX.setName("date");            //表格名称
        axisX.setTextSize(10);              //设置字体大小
        axisX.setMaxLabelChars(8);          //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisXValues.length
        //axisX.setValues(mAxisXValues);      //填充X轴的坐标名称
        lineChartData.setAxisXBottom(axisX);         //x 轴在底部
        //data.setAxisXTop(axisX);          //x 轴在顶部
        axisX.setHasLines(true);            //x 轴分割线

        // Y轴是根据数据的大小自动设置Y轴上限(在下面我会给出固定Y轴数据个数的解决方案)
        Axis axisY = new Axis();            //Y轴
        axisY.setName("");                  //y轴标注
        axisY.setTextSize(10);              //设置字体大小
        lineChartData.setAxisYLeft(axisY);           //Y轴设置在左边

        //设置行为属性，支持缩放、滑动以及平移
        chart_line.setInteractive(false);
        //chart_line.setZoomType(ZoomType.HORIZONTAL_AND_VERTICAL);
        //chart_line.setMaxZoom((float) 4);//最大方法比例
        chart_line.setZoomEnabled(false);
        chart_line.setContainerScrollEnabled(false, ContainerScrollType.HORIZONTAL);
        chart_line.setLineChartData(lineChartData);

        chart_line.setVisibility(View.VISIBLE);
    }

    List<Column> barColumns = new ArrayList<Column>();
    List<AxisValue> barAxisValues = new ArrayList<AxisValue>();
    int color_P = Color.parseColor("#00BFFF");
    int color_F = Color.BLUE;
    int color_T = Color.GREEN;
    int barAxisNums = 0;
    private void addBarChart(float maxForce, float maxPower, float durTimes) {

        //子列数据集合
        List<SubcolumnValue> values = new ArrayList<SubcolumnValue>();
        //遍历每一列的每一个子列
        //为每一柱图添加颜色和数值
        values.add(new SubcolumnValue(maxForce, color_F));
        values.add(new SubcolumnValue(maxPower, color_P));
        values.add(new SubcolumnValue(durTimes, color_T));

        //创建Column对象
        Column column = new Column(values);
        //这一步是能让圆柱标注数据显示带小数的重要一步 //作者回答https://github.com/lecho/hellocharts-android/issues/185
        ColumnChartValueFormatter chartValueFormatter = new SimpleColumnChartValueFormatter(1);
        column.setFormatter(chartValueFormatter);
        //是否有数据标注
        column.setHasLabels(true);
        //是否是点击圆柱才显示数据标注
        column.setHasLabelsOnlyForSelected(false);

        if(TestproSetup.usrID == ""){
            if(barColumns.size() == 10)
                barColumns.remove(0);
        }
        barColumns.add(column);
        //给x轴坐标设置描述
        barAxisValues.add(new AxisValue(barAxisNums++).setLabel("第"+barAxisNums+"次"));

        chart_bar.setColumnChartData(barData);      //给表填充数据，显示出来
    }

    private void initBarChart() {

        //创建一个带有之前圆柱对象column集合的ColumnChartData
        barData = new ColumnChartData(barColumns);

        //定义x轴y轴相应参数
        Axis axisX = new Axis().setHasLines(true);
        Axis axisY = new Axis().setHasLines(true);
        //axisY.setName("出场率(%)");//轴名称
        axisY.hasLines();//是否显示网格线
        //axisY.setTextColor(R.color.black);//颜色

        axisX.hasLines();
        axisX.setTextColor(R.color.black);
        axisX.setValues(barAxisValues);
        //把X轴Y轴数据设置到ColumnChartData 对象中
        barData.setAxisXBottom(axisX);
        barData.setAxisYLeft(axisY);

        chart_bar.setZoomEnabled(false);            //禁止手势缩放
        chart_bar.setColumnChartData(barData);      //给表填充数据，显示出来
    }

    private void startNewGroupTest(){
        now_group++;
        if(now_group > TestproSetup.getCurGroup()){
            endTotalTest(true);
            return;
        }
        is_now_group_started = true;
        now_freqs = 0;
        now_freq_maxPower = 0;  //清零
        now_freq_maxForce = 0;  //清零
        sub_max_power = new ArrayList<Float>();
        sub_max_force = new ArrayList<Float>();
        sub_dur_times = new ArrayList<Float>();
        freq_timeStart_ms.clear();
        group_startTime_ms      = System.currentTimeMillis();
        forceLineRaw.clear();
        forceLineCubic.clear();
        chart_line.setLineChartData(lineChartData);
        barAxisNums = 0;
        barColumns.clear();
        barAxisValues.clear();
    }

    @Override
    protected void onDestroy() {
        isQuitNow = true;
        if(read_thread != null){
            try {
                read_thread.join();
            } catch (InterruptedException e) {
                //e.printStackTrace();
            }
        }
        super.onDestroy();
    }
}